<template>
  <div class="comment-list">
    <span class="title">全部{{ type === "a" ? "评论" : "回复" }}</span>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <CommentItem
        :inReply="inReply"
        v-for="(comment, index) in list"
        :key="index"
        :comment="comment"
        @onLiking="onLiking"
      />
    </van-list>
  </div>
</template>

<script>
import { getArticles, addLiking, deteleLiking } from "@/api/comment";
import CommentItem from "./comment-item";

export default {
  name: "CommentList",
  props: {
    source: {
      required: true,
    },
    type: {
      default: "a",
    },
    inReply: {
      default: false,
    },
  },
  components: { CommentItem },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      offset: null, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取
      limit: 5,
    };
  },
  methods: {
    async onLoad() {
      const { data } = await getArticles({
        type: this.type,
        source: this.source,
        offset: this.offset,
        limit: this.limit,
      });

      const { results } = data.data;
      this.list.push(...results);

      this.loading = false;

      if (results.length) {
        this.offset = data.data.last_id;
      } else {
        this.finished = true;
      }
    },
    // 点赞评论
    async onLiking(comment) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
      });

      if (comment.is_liking) {
        await deteleLiking(comment.com_id);
        comment.like_count--;
      } else {
        await addLiking({
          target: comment.com_id,
        });
        comment.like_count++;
      }

      comment.is_liking = !comment.is_liking;
      this.$toast.success(`${comment.is_liking ? "" : "取消"}点赞成功`);
    },
  },
  mounted() {
    if (this.inReply) {
      // 回复评论成功事件
      this.$bus.$on("reply-success", (comment) => {
        this.list.unshift(comment);
      });
    } else {
      // 发布评论成功事件
      this.$bus.$on("post-success", (comment) => {
        this.list.unshift(comment);
      });
    }
  },
};
</script>

<style scoped lang="less">
.comment-list {
  margin-top: 15px;

  .title {
    font-size: 14px;
  }
}
</style>
